package com.wind.test;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.persistence.*;

public class JpaTest09_JPQL_改删 {

  private EntityManagerFactory entityManagerFactory;
  private EntityManager entityManager;
  private EntityTransaction entityTransaction;

  @Before
  public void init() {
    entityManagerFactory = Persistence.createEntityManagerFactory("JpaDemo");
    entityManager = entityManagerFactory.createEntityManager();
    entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();
  }

  @After
  public void destory() {
    entityTransaction.commit();
    entityManager.close();
    entityManagerFactory.close();
  }

  /*
    修改
   */
  @Test
  public void testUpdate() {
    String jpql = "UPDATE Cache SET name = ?, age = ? WHERE id = ?";
    Query query = entityManager.createQuery(jpql)
      .setParameter(1, "张三111")
      .setParameter(2, 15)
      .setParameter(new Integer(3), 1);
    query.executeUpdate();
  }

  /*
    删除
   */
  @Test
  public void testDelete() {
    String jpql = "DELETE FROM Cache WHERE id = ?";
    Query query = entityManager.createQuery(jpql)
      .setParameter( new Integer(1), 3);
    query.executeUpdate();
  }
}
